package com.lzxuni.config;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2019-01-24 19:34
 * @Modified BY:
 **/

//@Configuration
public class RestConfiguration {
	@Bean
//	@ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
	public RestTemplate restOperations() {
		//        SimpleClintHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		//        requestFactory.setReadTimeout(5000);
		//        requestFactory.setConnectTimeout(5000);
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
		} catch (Exception e) {
			//  e.printStackTrace();
		}
		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
		clientHttpRequestFactory.setReadTimeout(2000);
		clientHttpRequestFactory.setConnectTimeout(2000);
		RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);


		// 使用 utf-8编码集的 conver 替换默认的 conver（默认的 string conver 的编码集为 "ISO-8859-1"）
		List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
		Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
		while (iterator.hasNext()) {
			HttpMessageConverter<?> converter = iterator.next();
			if (converter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) converter).setDefaultCharset(Charset.forName("utf-8"));
			}
		}
		// 解决text/plain的，比如微信等
		restTemplate.getMessageConverters().add(new NewMappingJackson2HttpMessageConverter());
		return restTemplate;
	}
	/* 由于默认构造的MappingJackson2HttpMessageConverter中的supportedMediaTypes只支持：applicantion/json的，所以再添加MediaType.TEXT_PLAIN的MediaType的支持
	 */
	public static final class NewMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
		public NewMappingJackson2HttpMessageConverter() {
			List<MediaType> mediaTypes = new ArrayList<>();
			mediaTypes.add(MediaType.TEXT_PLAIN);
			setSupportedMediaTypes(mediaTypes);
		}
	}
}

